<template>
  <div>
    <!-- 导航面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索输入框区域 -->
          <el-input v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="addUserDialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表格区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="username"
          label="日期"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserInfo(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="设置权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightsDigo(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="addUserDialogFormVisible" width="50%">
      <el-form :model="addUser" ref="addUserRef" :rules="addUserRule">
        <el-form-item label="用户名" label-width="70px" prop="username">
          <el-input v-model="addUser.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="70px" prop="password">
          <el-input v-model="addUser.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
         <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="addUser.email" autocomplete="off"></el-input>
        </el-form-item>
         <el-form-item label="电话" label-width="70px" prop="mobile">
          <el-input v-model="addUser.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddUser">取 消</el-button>
        <el-button type="primary" @click="submitAddUser"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
  title="修改用户"
  :visible.sync="editUserDialogVisible"
  width="50%">
  <el-form :model="editUser" ref="editUserRef" :rules="editUserRule">
        <el-form-item label="用户名" label-width="70px">
          <el-input v-model="editUser.username" autocomplete="off" disabled></el-input>
        </el-form-item>
         <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="editUser.email" autocomplete="off"></el-input>
        </el-form-item>
         <el-form-item label="电话" label-width="70px" prop="mobile">
          <el-input v-model="editUser.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
  <span slot="footer">
    <el-button @click="cancelEditUser">取 消</el-button>
    <el-button type="primary" @click="submitEditUser">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="设置权限"
  :visible.sync="setRightsDialogVisible"
  width="50%"
  @close="clearSetRightsList"
  >
  <p>当前用户：{{setRightsUserInfo.username}}</p>
  <p>当前用户：{{setRightsUserInfo.role_name}}</p>
  <p>分配新角色：
    <el-select v-model="checkedRoleId" placeholder="请选择" @change="showID">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id"
      >
    </el-option>
  </el-select>
  </p>
  <span slot="footer">
    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="subSetRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  name: 'users',
  data () {
    let checkEmail = (rule, value, callback) => {
      const emailReg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/
      if (!emailReg.test(value)) {
        return callback(new Error('请输入合法的邮箱地址'))
      }
      callback()
    }
    let checkMobile = (rule, value, callback) => {
      const mobileReg = /^1[3456789]\d{9}$/
      if (!mobileReg.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      }
      callback()
    }
    return {
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页的数量
        pagesize: 2
      },
      // 存放用户信息
      userList: [],
      // 用户总数量
      total: 0,
      // 控制添加用户表单的显示与否
      addUserDialogFormVisible: false,
      // 用于存放添加用户的对象
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户的规则
      addUserRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3-10之间的用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '请输入6-15之间的用户名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserDialogVisible: false,
      editUser: {},
      editUserRule: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRightsDialogVisible: false,
      setRightsUserInfo: {},
      rolesList: [],
      checkedRoleId: ''
    }
  },
  methods: {
    // 利用axios从后台获取用户数据
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        // get传递查询参数
        params: this.queryInfo
      })
      console.log(res)
      // 利用状态判断是否获取数据成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听一页数量的变化
    handleSizeChange (newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getUserList()
    },
    // 监听当前页码的变化
    handleCurrentChange (newCurrentPage) {
      this.queryInfo.pagenum = newCurrentPage
      this.getUserList()
    },
    // 利用axios改变用户状态
    async changeUserState (userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    cancelAddUser () {
      this.$refs.addUserRef.resetFields()
      this.addUserDialogFormVisible = false
    },
    submitAddUser () {
      this.$refs.addUserRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUser)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.getUserList()
      })
      this.addUserDialogFormVisible = false
    },
    async editUserInfo (id) {
      this.editUserDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) return
      this.editUser = res.data
    },
    cancelEditUser () {
      this.$refs.editUserRef.resetFields()
      this.editUserDialogVisible = false
    },
    submitEditUser () {
      this.$refs.editUserRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editUser.id, {
          email: this.editUser.email,
          mobile: this.editUser.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        this.getUserList()
      })
      this.editUserDialogVisible = false
    },
    async deleteUser (id) {
      console.log(id)
      const userResponse = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(userResponse)
      // 当用户确定删除会返回值 confirm
      // 当用户取消删除时会返回值 cancel
      if (userResponse !== 'confirm') return this.$message.info('您取消了删除用户')
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    async showSetRightsDigo (role) {
      this.setRightsDialogVisible = true
      this.setRightsUserInfo = role
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    async subSetRights () {
      const { data: res } = await this.$http.put(`users/${this.setRightsUserInfo.id}/role`, {
        rid: this.checkedRoleId
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新用户角色失败')
      this.$message.success(res.meta.msg)
      this.setRightsDialogVisible = false
      this.getUserList()
    },
    showID () {
      console.log(this.checkedRoleId)
    },
    clearSetRightsList () {
      this.checkedRoleId = ''
    }
  },
  created () {
    // 在页面组件加载阶段创造数据
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
.el-col {
  display: flex;
  align-items: center;
}
</style>
